package api_http

import (
	"context"
	"github.com/gin-gonic/gin"
	"go-fast/app/api_http/router"
	"go-fast/global"
	"go-fast/pkg/http/middleware"
	"net/http"
	"strconv"
	"time"
)

type ApiHttp struct {
	srv *http.Server
}

func NewApiHttpServer() ApiHttp {
	conf := global.Conf.Http

	r := gin.New()
	// 添加中间件
	r.Use(middleware.GinLogger(global.Log))
	r.Use(middleware.Cors())
	r.Use(middleware.Recovery())

	// 注册路由
	router.RegisterUser(r)

	srv := &http.Server{
		Addr:         ":" + strconv.Itoa(conf.ListenPort),
		Handler:      r,
		ReadTimeout:  time.Duration(conf.ReadTimeout) * time.Second,
		WriteTimeout: time.Duration(conf.WriteTimeout) * time.Second,
	}
	return ApiHttp{srv: srv}
}

// Run 启动http服务
func (a *ApiHttp) Run() error {
	global.Log.Infof("http server listen to %+v", a.srv.Addr)
	return a.srv.ListenAndServe()
}

// Shutdown 关闭http服务
func (a *ApiHttp) Shutdown(ctx context.Context) error {
	return a.srv.Shutdown(ctx)
}
